<?php

namespace app\stores\logic;

use app\beautiful\logic\PartnerLogic;

use app\beautiful\logic\printer\PrinterLogic;
use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\PinTuanGoodsModel;

use app\beautiful\model\mall\PinTuanGoodsSkuModel;

use app\beautiful\model\mall\PinTuanGroupModel;

use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\order\GoodsOrderItemModel;

use app\beautiful\model\order\GoodsOrderModel;

use app\beautiful\model\order\OrderGoodsGroupDetailModel;
use app\beautiful\model\order\OrderGoodsGroupModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\beautiful\model\order\PinTuanOrderItemModel;

use app\beautiful\model\order\PinTuanOrderModel;

use app\beautiful\helper\payment\PaymentPintuanOrderHelper;

use app\beautiful\logic\MemberWalletLogic;
use app\stores\model\pintuan\GoodsPinTuanModel;

class PinTuanLogic{

    protected $shopId;

    protected $member;

    protected $order;

    protected $order_item;

    protected $pin_tuan_goods;

    protected $pin_tuan_group;

    protected $complete_pin_tuan_order;

    protected $pin_tuan_goods_data;

    protected $pin_tuan_sku_datas;

    public function __construct($shopId)

    {

        $this->shopId=$shopId;

    }



    public function cancelPay($params)

    {

        $this->checkMember($params['member_id'],false);

        $this->checkOrder($params['order_id'],true);



//        if($this->order->is_delete != 0) $this->error('订单不存在');

        if($this->order->is_paid == 1 || $this->order->status != 1) $this->error('订单无法取消');



        $this->order->status=-3;

        $this->order->save();



        $this->pin_tuan_goods_data=[];$this->pin_tuan_sku_datas=[];

        $this->cancelGoods();



        //保存拼团商品

        $pin_tuan_goods_model=new PinTuanGoodsModel();

        $pin_tuan_goods_model->saveAll($this->pin_tuan_goods_data);



        //保存拼团规格

        $pin_tuan_goods_sku_model = new PinTuanGoodsSkuModel();

        $pin_tuan_goods_sku_model->saveAll($this->pin_tuan_sku_datas);

        return true;

    }



    public function payOk($params)

    {

        $this->checkMember($params['member_id'],false);

        $this->checkOrder($params['order_id'],true);

        if($this->order->is_paid !=1 || $this->order->status != 2) $this->error('订单状态不对');



        $this->checkOrderItem($this->order->pin_tuan_order_id,true);

        $this->checkPinTuanGoods($this->order_item->goods_id,true);



        $this->getGroupId($this->order->pin_tuan_group_id);

        $this->order->pin_tuan_group_id=$this->pin_tuan_group->pin_tuan_group_id;

        if($this->pin_tuan_group->chief_id == $this->member->member_id){

            $this->order->is_chief = 1;

        }

        $this->order->save();

        $this->pin_tuan_group->num=$this->pin_tuan_group->num+1;

        $this->pin_tuan_group->save();

        

        if($this->checkGroupStatus()){

            $this->completeGroupAct();

        }



    }



    public function fakeGroup($pin_tuan_group_id)

    {

        $this->checkGroup($pin_tuan_group_id);

        if($this->pin_tuan_group->status != 1) $this->error('拼团已完成或者已取消');

        if($this->pin_tuan_group->group_size > $this->pin_tuan_group->num) $this->error('团员人数不够，无法成团');

        $num=PinTuanOrderModel::where([

                ['shop_id','=',$this->shopId],

                ['pin_tuan_group_id','=',$this->pin_tuan_group->pin_tuan_group_id],

                ['status','in',[2,3]],

            ])->count() ?? 0;

        if($this->pin_tuan_group->group_size > $num) $this->error('团员人数不够，无法成团');



        $this->completeGroupAct();



    }





    public function cancelPinTuan($params)

    {

        $this->checkMember($params['member_id'],false);

        $this->checkOrder($params['order_id'],true);

        if($this->order->is_paid == 0 || $this->order->status != 2) $this->error('订单状态不对');



        $this->checkGroup($this->order->pin_tuan_group_id);

        if($this->pin_tuan_group->group_size<=$this->pin_tuan_group->num) $this->error('拼团已完成');

        if($this->pin_tuan_group->status != 1) $this->error('拼团已完成或者已取消');



        $this->order->status=-1;

        $this->order->save();




        $this->pin_tuan_goods_data=[];$this->pin_tuan_sku_datas=[];

        $this->cancelGoods();




        //保存拼团商品

        $pin_tuan_goods_model=new PinTuanGoodsModel();

        $pin_tuan_goods_model->saveAll($this->pin_tuan_goods_data);


        //保存拼团规格

        $pin_tuan_goods_sku_model = new PinTuanGoodsSkuModel();

        $pin_tuan_goods_sku_model->saveAll($this->pin_tuan_sku_datas);



        if($this->order->pay_type=='weixin'){

            $this->cancelPinTuanweixin();

        }else if($this->order->pay_type=='platform_money') {

            $this->cancelPinTuanPlatformMoney();
        }else{

            $this->cancelPinTuanMoney();

        }



        //如果是团长重新选择团长；如果没有人能选择就直接拼团失败

        if($this->order->is_chief==1){

            if(null !== $new_chief=PinTuanOrderModel::where([

                ['shop_id','=',$this->shopId],

                ['is_chief','=',0],

                ['pin_tuan_group_id','=',$this->order->pin_tuan_group_id],

                ['status','=',2],

            ])->find()){

                $new_chief->is_chief=1;

                $new_chief->save();



                $this->order->is_chief=0;

                $this->order->is_paid=0;

                $this->order->save();



                $this->pin_tuan_group->chief_id=$new_chief->member_id;

                $this->pin_tuan_group->num = $this->pin_tuan_group->num -1;

                $this->pin_tuan_group->save();

            }else{

                $this->pin_tuan_group->status=-1;

                $this->pin_tuan_group->save();

                $order_datas=PinTuanOrderModel::where([

                    ['shop_id','=',$this->shopId],

                    ['pin_tuan_group_id','=',$this->order->pin_tuan_group_id],

                    ['status','=',1],

                ])->select()->toArray();

                if(!empty($order_datas)){

                    foreach ($order_datas as $k => $v){

                        $this->cancelPay([

                            'member_id'=>$this->member->member_id,

                            'order_id'=>$v['pin_tuan_order_id']

                        ]);

                    }

                }

            }

        }



    }

    protected function cancelPinTuanPlatformMoney()

    {

        if(!empty($this->order->member_coupon_id)){

            if(null === $myCoupon = MemberCouponModel::find($this->order->member_coupon_id)){

                $this->error('优惠券不存在');

            }

            if($myCoupon->status == 0){

                $this->error('优惠券还未使用');

            }

            $myCoupon->status = 0;

            $myCoupon->save();

            LogsLogic::coupon($this->shopId, $this->member->member_id, 1, 13, $this->order->member_coupon_id, '', 0);

        }

        $MemberWalletLogic = new MemberWalletLogic($this->shopId, $this->member->member_id);

        if(!empty($this->order->use_integral)){ //使用积分

            $res = $MemberWalletLogic->addIntegal($this->order->use_integral, 10);

            if($res == false){

                $this->error($MemberWalletLogic->getError());

            }

        }


        $MemberWalletLogic = new \app\stores\logic\MemberWalletLogic($this->shopId, $this->member->member_id);

        $res = $MemberWalletLogic->rebackPlatformMoney($this->order->need_pay, 0 , 9,0,0,$this->order->pin_tuan_order_id); //商城购物使用

        if($res == false){

            $this->error($MemberWalletLogic->getError());

        }



        $this->order->status=-2;

        $this->order->save();

    }

    protected function cancelPinTuanMoney()

    {

        if(!empty($this->order->member_coupon_id)){

            if(null === $myCoupon = MemberCouponModel::find($this->order->member_coupon_id)){

                $this->error('优惠券不存在');

            }

            if($myCoupon->status == 0){

                $this->error('优惠券还未使用');

            }

            $myCoupon->status = 0;

            $myCoupon->save();

            LogsLogic::coupon($this->shopId, $this->member->member_id, 1, 13, $this->order->member_coupon_id, '', 0);

        }

        $MemberWalletLogic = new MemberWalletLogic($this->shopId, $this->member->member_id);

        if(!empty($this->order->use_integral)){ //使用积分

            $res = $MemberWalletLogic->addIntegal($this->order->use_integral, 10);

            if($res == false){

                $this->error($MemberWalletLogic->getError());

            }

        }



        $res = $MemberWalletLogic->rebackBalance($this->order->need_pay, 0 , 9); //商城购物使用

        if($res == false){

            $this->error($MemberWalletLogic->getError());

        }



        $this->order->status=-2;

        $this->order->save();

    }



    protected function cancelPinTuanweixin()

    {



        if(!empty($this->order->member_coupon_id)){

            if(null === $myCoupon = MemberCouponModel::find($this->order->member_coupon_id)){

                $this->error('优惠券不存在');

            }

            if($myCoupon->status == 0){

                $this->error('优惠券还未使用');

            }

            $myCoupon->status = 0;

            $myCoupon->save();

            LogsLogic::coupon($this->shopId, $this->member->member_id, 1, 13, $this->order->member_coupon_id, '', 0);

        }

        $MemberWalletLogic = new MemberWalletLogic($this->shopId, $this->member->member_id);

        if(!empty($this->order->use_integral)){ //使用积分

            $res = $MemberWalletLogic->addIntegal($this->order->use_integral, 10);

            if($res == false){

                $this->error($MemberWalletLogic->getError());

            }

        }

//        //补充

//        $res = $MemberWalletLogic->rebackBalance($this->order->need_pay, 0 , 9); //商城购物使用

//        if($res == false){

//            $this->error($MemberWalletLogic->getError());

//        }

        //支付原路退还

        $PaymentPintuanOrderHelper = new PaymentPintuanOrderHelper($this->shopId);

        $PaymentPintuanOrderHelper->refundInTheSameWay($this->order->pay_info);

        

        $this->order->status=-2;

        $this->order->save();



    }



    protected function completeGroupAct()

    {

        //拼团团队处理

        $this->pin_tuan_group->status=2;

        $this->pin_tuan_group->save();



        //团队订单处理

        $pin_tuan_order_data=PinTuanOrderModel::with(['item'])->where([

            ['shop_id','=',$this->shopId],

            ['pin_tuan_group_id','=',$this->pin_tuan_group->pin_tuan_group_id],

            ['member_id','<>',0]

        ])->select()->toArray();

        $this->complete_pin_tuan_order=[];

        foreach ($pin_tuan_order_data as $k => $v){

            //待付款直接取消拼团

            if($v['status']==1){

                $this->cancelPay([

                    'member_id'=>$v['member_id'],

                    'order_id'=>$v['pin_tuan_order_id']

                ]);

            }

            //待成团 成团

            if($v['status']==2 && $v['is_real']==1){

                $this->complete_pin_tuan_order[]=$v;

            }

        }

        $this->completeGroupOrder();

    }



    protected function completeGroupOrder()

    {

        $complete_pin_tuan_order=$this->complete_pin_tuan_order;

        $order_item_data=[];

        $g_model = new GoodsModel();
        foreach ($complete_pin_tuan_order as $k => $v){

            $order_data=[];

            $complete_pin_tuan_order[$k]['status']=3;

            $status = $v['logistics_type']==1 ? 2 : 4;

            if($v['logistics_type'] == 3) $status = 9;

            //拼团商品
            $ptg = PinTuanGroupModel::with(['pinTuanGoods'])->where(['pin_tuan_group_id'=>$v['pin_tuan_group_id']])->find();
            $ptg = $ptg->toArray();
            $goods = $g_model->getById(['goods_id'=>$ptg['pinTuanGoods']['goods_id']]);

            if($goods['type'] == 3) $status = 10;

            $order_data=[

                'shop_id'=>$this->shopId,

                'order_type'=>'pin_tuan',

                'logistics_type'=>$v['logistics_type'],

                'freight_type'=>$v['freight_type'],

                'hours'=>$v['hours'],

                'member_id'=>$v['member_id'],

                'pin_tuan_group_id'=>$v['pin_tuan_group_id'],

                'pin_tuan_order_id'=>$v['pin_tuan_order_id'],

                'total_price'=>$v['total_price'],

                'need_pay'=>$v['need_pay'],

                'freight'=>$v['freight'],

                'member_coupon_id'=>$v['member_coupon_id'],

                'coupon_money'=>$v['coupon_money'],

                'use_integral'=>$v['use_integral'],

                'integral_balance'=>$v['integral_balance'],

                'pay_type'=>$v['pay_type'],

                'is_paid'=>$v['is_paid'],

                'status'=>$status,

                'pay_time'=>$v['pay_time'],

                'pay_info'=>$v['pay_info'],

                'receiving_name'=>$v['receiving_name'],

                'receiving_mobile'=>$v['receiving_mobile'],

                'receiving_address_province'=>$v['receiving_address_province'],

                'receiving_address_city'=>$v['receiving_address_city'],

                'receiving_address_county'=>$v['receiving_address_county'],

                'receiving_address_info'=>$v['receiving_address_info'],

                'order_send_time'=>$v['order_send_time'],

                'from_type'=>$v['from_type'],

                'edit_time'=>date('Y-m-d H:i:s'),

                'mix_pay_type'=>$v['mix_pay_type'],

                'platform_money'=>$v['platform_money'],

                'money'=>$v['money'],

                'weixin'=>$v['weixin']
            ];

            $order_model= new GoodsOrderModel();

            $order_model->save($order_data);

            GoodsOrderModel::where(['order_id'=>$order_model->order_id])->save(['order_sn'=>createOrderSn($order_model->order_id,3),'verify_code'=>getVerifyCode($order_model->order_id)]);

            //记录推广者佣金

            //增加积分操作

            if($v['pay_type'] == 'weixin'){

                $MemberWalletLogic = new MemberWalletLogic($this->shopId,$v['member_id']);

                $MemberWalletLogic->addIntegralByPayment($v['need_pay']); //更新支付返的积分

            }

            //分红
//            $PartnerLogic = new PartnerLogic($this->shopId);
//            $PartnerLogic->commissionNew($v['member_id'],$v['need_pay'],'pintuanOrder',$v['pin_tuan_order_id']);


            foreach ($v['item'] as $key => $val){
                //分类
                $category = GoodsCategoryModel::where(['shop_id'=>$goods['shop_id'],'category_id'=>$goods['category_id'],'is_delete'=>0])->find();

                $order_item_data[]=[

                    'shop_id'=>$this->shopId,

                    'order_id'=>$order_model->order_id,

                    'goods_type'=>'pin_tuan',

                    'goods_id'=>$val['goods_id'],

                    'category_name'=>$category?$category->name:null,

                    'goods_name'=>$val['goods_name'],

                    'goods_cover_img'=>$val['goods_cover_img'],

                    'goods_sku_id'=>$val['goods_sku_id'],

                    'goods_sku_name'=>$val['goods_sku_name'],

                    'goods_original_price'=>$val['goods_original_price'],

                    'group_size'=>$val['group_size'],

                    'goods_price'=>$val['goods_price'],

                    'goods_gross'=>$val['goods_gross'],

                    'goods_num'=>$val['goods_num'],

                    'type'=>$goods['type']

                ];


            }
            //获取打印订单id
            $order_ids[] = ['order_id'=>$order_model->order_id,'logistics_type'=>$order_data['logistics_type']];

        }

        $pin_tuan_order_model= new PinTuanOrderModel();

        $pin_tuan_order_model->saveAll($complete_pin_tuan_order);


        $order_item_model = new GoodsOrderItemModel();

        $order_item_model->saveAll($order_item_data);
        //分区打印
        foreach ($order_ids as $k=>$v){
            //打印机
            if($v['logistics_type'] == 1){
                $type = 'kuaidi';
            }
            if($v['logistics_type'] == 2){
                $type = 'self';
            }
            if($v['logistics_type'] == 3){
                $type = 'city';
            }
            if(in_array($v['logistics_type'],[1,2,3])){
                //判断是否有分区打印的产品
                $return_goods_produce = goodsProduce($v['order_id']);
                $prints = $return_goods_produce['prints'];
                $produce_printer_ids = [];
                if($prints){
                    $printer_logic = new \app\stores\logic\printer\PrinterLogic($this->shopId);
                    $produce_printer_ids = $printer_logic->producePrint($type,$v['order_id'],$prints);
                }

            }
        }

    }



    /**

     * 获取组团数据

     * @param $pin_tuan_group_id

     * @throws \think\db\exception\DataNotFoundException

     * @throws \think\db\exception\DbException

     * @throws \think\db\exception\ModelNotFoundException

     */

    protected function getGroupId($pin_tuan_group_id)

    {

        if($pin_tuan_group_id==0){

            $pin_tuan_group=new PinTuanGroupModel();

            $pin_tuan_group->shop_id= $this->shopId;

            $pin_tuan_group->chief_id= $this->member->member_id;

            $pin_tuan_group->pin_tuan_goods_id=$this->pin_tuan_goods->pin_tuan_goods_id;

            $pin_tuan_group->group_size=$this->pin_tuan_goods->group_num;

            $pin_tuan_group->save();

        }else{

            $pin_tuan_group=PinTuanGroupModel::find($pin_tuan_group_id);

            if($pin_tuan_group === null) $this->error('拼团团队不存在');

            if($pin_tuan_group->shop_id != $this->shopId) $this->error('拼团团队不存在');

            if($pin_tuan_group->group_size<=$pin_tuan_group->num) $this->error('拼团已完成');

            if($pin_tuan_group->status != 1) $this->error('拼团已完成或者已取消');

            if(($pin_tuan_group->add_time+86400)<time()) $this->error('此拼团已超过期限');

        }

        $this->pin_tuan_group=$pin_tuan_group;

    }



    public function checkGroup($pin_tuan_group_id)

    {

        $pin_tuan_group=PinTuanGroupModel::find($pin_tuan_group_id);

        if($pin_tuan_group === null) $this->error('拼团团队不存在');

        if($pin_tuan_group->shop_id != $this->shopId) $this->error('拼团团队不存在');

        $this->pin_tuan_group=$pin_tuan_group;



    }





    /**

     * 判断团现在的状态
     * group_size  现在拼团人数 >= 需要成团人数  ，成团
     * @return bool

     */

    protected function checkGroupStatus()

    {

        $status=false;

        if($this->pin_tuan_group->group_size <= $this->pin_tuan_group->num){

            $num=PinTuanOrderModel::where([

                ['shop_id','=',$this->shopId],

                ['pin_tuan_group_id','=',$this->pin_tuan_group->pin_tuan_group_id],

                ['status','=',2],

            ])->count() ?? 0;

            if($this->pin_tuan_group->group_size <= $num){

                $status=true;

            }

        }

        return $status;

    }



    protected function checkOrder($orderId,$lock)

    {

        empty($orderId) &&  $this->error('请选择要支付的订单');

        if(null === $this->order = PinTuanOrderModel::where('pin_tuan_order_id',$orderId)->lock($lock)->find()){

            $this->error('订单不存在');

        }
        $this->shopId = $this->order->shop_id;

//        if($this->member->shop_id != $this->shopId){
//
//            $this->error('订单不存在');
//
//        }

    }



    protected function checkOrderItem($orderId,$lock)

    {

        empty($orderId) &&  $this->error('请选择要支付的订单');

        if(null === $this->order_item = PinTuanOrderItemModel::where('pin_tuan_order_id',$orderId)->lock($lock)->find()){

            $this->error('订单不存在');

        }

//        if($this->member->shop_id != $this->shopId){
//
//            $this->error('订单不存在');
//
//        }

    }



    protected function checkPinTuanGoods($goods_id,$lock)

    {

        empty($goods_id) &&  $this->error('拼团商品不存在');

        if(null === $this->pin_tuan_goods = PinTuanGoodsModel::where('pin_tuan_goods_id',$goods_id)->lock($lock)->find()){

            $this->error('拼团商品不存在');

        }

//        if($this->member->shop_id != $this->shopId){
//
//            $this->error('拼团商品不存在');
//
//        }

    }



    protected function checkMember($memberId,$lock = true){

        empty($memberId) && $this->error ('用户未登录');

        if(null === $this->member = MemberModel::where('member_id',$memberId)->lock($lock)->find()){

            $this->error('用户未登录');

        }

//        ($this->member->shop_id != $this->shopId) && $this->error('用户不是该APP的');

    }



    protected function cancelGoods()

    {

        $order_item_data=PinTuanOrderItemModel::where([

            ['shop_id','=',$this->shopId],

            ['pin_tuan_order_id','=',$this->order->pin_tuan_order_id],

        ])->field('goods_id,goods_sku_id,goods_num')->select()->toArray();

        $goods_ids=[];$sku_ids=[];$order_item_array=[];



        if(!empty($order_item_data)){

            foreach ($order_item_data as $k => $v){

                $goods_ids[]=$v['goods_id'];

                $sku_ids[]=$v['goods_sku_id'];

                $order_item_array['goods'][$v['goods_id']]=$v;

                $order_item_array['sku'][$v['goods_sku_id']]=$v;

            }

        }



        //处理秒杀商品

        $pin_tuan_goods_data=PinTuanGoodsModel::where([

            ['shop_id','=',$this->shopId],

            ['pin_tuan_goods_id','in',$goods_ids],

        ])->field('pin_tuan_goods_id,quota,take_count,fictitious_take_count')->select()->toArray();



        foreach ($pin_tuan_goods_data as $k => $v){

            $num=$order_item_array['goods'][$v['pin_tuan_goods_id']]['goods_num'] ?? 0;

            $pin_tuan_goods_data[$k]['quota']=$v['quota'] +$num;

            $pin_tuan_goods_data[$k]['fictitious_take_count']=($v['fictitious_take_count'] -$num) <=0 ? $v['fictitious_take_count'] : ($v['fictitious_take_count'] -$num);

            $pin_tuan_goods_data[$k]['take_count']=$v['take_count'] -$num;

        }

        $this->pin_tuan_goods_data=$pin_tuan_goods_data;



        //处理规格

        $pin_tuan_sku_datas=PinTuanGoodsSkuModel::where([

            ['shop_id','=',$this->shopId],

            ['pin_tuan_goods_sku_id','in',$sku_ids],

        ])->field('pin_tuan_goods_sku_id,quota,take_count')->select()->toArray();



        foreach ($pin_tuan_sku_datas as $k => $v){

            $num=$order_item_array['sku'][$v['pin_tuan_goods_sku_id']]['goods_num'] ?? 0;

            $pin_tuan_sku_datas[$k]['quota']=$v['quota'] +$num;

            $pin_tuan_sku_datas[$k]['take_count']=$v['take_count'] -$num;

        }

        $this->pin_tuan_sku_datas=$pin_tuan_sku_datas;

    }





    public function error($message){

        throw new \Exception($message);

    }

}

